"""
FastAPI 应用入口
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.core.database import init_db
from app.core.logger import logger
from app.core.middleware import APILoggerMiddleware
from app.api.v1 import api_router
from app.api.v2 import router as admin_router

# 创建 FastAPI 应用
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="足球场预约系统 API",
    docs_url="/docs",
    redoc_url="/redoc"
)

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=settings.CORS_ALLOW_CREDENTIALS,
    allow_methods=settings.CORS_ALLOW_METHODS,
    allow_headers=settings.CORS_ALLOW_HEADERS,
)

# 添加 API 日志中间件
app.add_middleware(APILoggerMiddleware)

# 注册路由
app.include_router(api_router, prefix="/api/v1")
app.include_router(admin_router)  # v2 路由已包含 /api/v2 前缀


@app.on_event("startup")
async def startup_event():
    """应用启动事件"""
    logger.info(f" {settings.APP_NAME} v{settings.APP_VERSION} 启动中...")
    logger.info(f" API 文档: http://{settings.HOST}:{settings.PORT}/docs")
    logger.info(f" 数据库: {settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}")
    
    # 初始化数据库（创建表）
    try:
        logger.info("⏳ 正在初始化数据库...")
        init_db()
        logger.success("✅ 数据库初始化成功")
    except Exception as e:
        logger.error(f"❌ 数据库初始化失败: {e}")
        logger.warning("   请检查数据库配置和网络连接")
    
    # 初始化 MinIO 服务
    try:
        from app.services.minio_service import minio_service
        if minio_service:
            logger.success(f"✅ MinIO 服务已就绪: {settings.MINIO_ENDPOINT}/{settings.MINIO_BUCKET}")
        else:
            logger.warning("⚠️  MinIO 服务未配置或不可用")
    except Exception as e:
        logger.warning(f"⚠️  MinIO 服务初始化警告: {e}")


@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭事件"""
    logger.info(f" {settings.APP_NAME} 正在关闭...")


@app.get("/")
async def root():
    """根路径"""
    return {
        "name": settings.APP_NAME,
        "version": settings.APP_VERSION,
        "message": "足球场预约系统 API 服务正在运行",
        "docs": "/docs"
    }


@app.get("/health")
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "version": settings.APP_VERSION
    }


if __name__ == "__main__":
    import uvicorn
    
    uvicorn.run(
        "main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.DEBUG
    )

